// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID;

  try {
    const { printerId, fileUrl, fileName, printOptions, totalPrice } = event;

    // 生成一个简单的取件码（例如：4位随机数）
    const pickCode = Math.random().toString().slice(-4);

    const orderData = {
      _openid: openid, // 订单所属用户
      printerId: printerId,
      fileUrl: fileUrl,
      fileName: fileName,
      printOptions: printOptions,
      totalPrice: totalPrice,
      payStatus: 'paid', // 默认为已支付 (模拟)
      printStatus: 'pending', // 打印状态：pending (待打印), printing (打印中), completed (已完成)
      createTime: new Date(),
      pickCode: pickCode
    };

    const newOrder = await db.collection('orders').add({
      data: orderData
    });

    return {
      success: true,
      orderId: newOrder._id
    }

  } catch (e) {
    console.error('创建订单失败', e);
    return {
      success: false,
      error: e
    }
  }
}